import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:image_preview/model/DataProvider.dart';
import 'package:image_preview/ui/InitPlaceHolder.dart';
import 'package:image_preview/ui/MyHomePage.dart';

import 'image/widget/imagePreviewPage.dart';
import 'imagepreview/widget/image_preview_widget.dart';
import 'ui/ImageScanWidget.dart';

void main() async {
  // 下载器
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterDownloader.initialize(debug: true);
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const MethodChannel _channel =
      MethodChannel('com.example.android_native_with_flutter/route');

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    _channel.setMethodCallHandler((call) async {
      if (call.method == 'setInitialRoute') {
        String route = call.arguments;
        if (kDebugMode) {
          print("ImagePreview: MyApp setMethodCallHandler = $route");
        }
        // Navigator.of(context).pushNamed(route);
      }
    });
    if (kDebugMode) {
      print("ImagePreview: MyApp build开始.");
    }
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter', items: DataProvider.params),
      onGenerateRoute: (settings) {
        String route = settings.name!;
        switch (settings.name) {
          case "/":
            return MaterialPageRoute(
              builder: (context) => const InitPlaceHolder(),
            );
          case "/image/preview":
            return MaterialPageRoute(
                builder: (context) => const Imagescanwidget());
          case "/image/preview2":
            return MaterialPageRoute(
                builder: (context) => const ImagePreviewWidget());
          case "/image/preview3":
            return MaterialPageRoute(builder: (context) => const ImageWidget());
          case "/home":
            return MaterialPageRoute(
                builder: (context) =>
                    const MyHomePage(title: '主页', items: DataProvider.params));
          default:
            if (kDebugMode) {
              print("ImagePreview: MyApp route = $route");
            }
            // 处理未知路由
            return MaterialPageRoute(
              builder: (context) => Scaffold(
                body: Center(
                  child: Text(_formatNotFoundMessage(route)),
                ),
              ),
            );
        }
      },
    );
  }

  // 定义一个辅助函数来格式化错误信息
  String _formatNotFoundMessage(String? route) {
    // 确保 route 不为 null 或空字符串
    final safeRoute = route?.isNotEmpty == true ? route : '未知路径';

    // 返回格式化后的错误信息
    return 'Page not found: $safeRoute';
  }
}
